package com.charge.service.impl;

import com.charge.dao.AccountMapping;
import com.charge.dao.TransferRecordMapping;
import com.charge.domain.Account;
import com.charge.domain.TransferRecord;
import com.charge.dto.TransferImportDTO;
import com.charge.dto.TransferRecordDTO;
import com.charge.service.TransferRecordService;
import com.charge.vo.TransferRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Description :
 * Author : 91658
 * Date : 2018/6/20 16:13
 **/
@Service
public class TransferRecordServiceImpl implements TransferRecordService {

    @Autowired
    private TransferRecordMapping transferRecordMapping;

    @Autowired
    private AccountMapping accountMapping;

    @Override
    public Integer selectTransferRecordCount(TransferRecordDTO transferRecordDTO) {
        return transferRecordMapping.selectTransferRecordCount(transferRecordDTO);
    }

    @Override
    public List<TransferRecordVO> selectTransferRecordList(TransferRecordDTO transferRecordDTO) {
        return transferRecordMapping.selectTransferRecordList(transferRecordDTO);
    }

    @Override
    @Transactional
    public void importTransferRecord(List<TransferImportDTO> transferImportDTOList) {
        for (TransferImportDTO importDTO : transferImportDTOList) {
            TransferRecord transferRecord = new TransferRecord();
            transferRecord.setUserId(1);

            Account fromAccount = accountMapping.selectAccountByName(importDTO.getFromAccountName());
            if (fromAccount == null) {
                throw new RuntimeException("转出账户不存在");
            }
            transferRecord.setFromAccountId(fromAccount.getId());

            Account toAccount = accountMapping.selectAccountByName(importDTO.getToAccountName());
            if (toAccount == null) {
                throw new RuntimeException("转入账户不存在");
            }
            transferRecord.setToAccountId(toAccount.getId());

            transferRecord.setTransferMoney(importDTO.getTransferMoney());
            transferRecord.setPoundage(importDTO.getPoundage());

            Account poundageAccount = accountMapping.selectAccountByName(importDTO.getPoundageWayName());
            if (poundageAccount == null) {
                throw new RuntimeException("手续费扣除方所在账户不存在");
            }
            if (poundageAccount.getId().equals(fromAccount.getId())) {
                transferRecord.setPoundageWay(1);
            } else if(poundageAccount.getId().equals(toAccount.getId())) {
                transferRecord.setPoundageWay(2);
            }

            transferRecord.setTransferRemark(importDTO.getTransferRemark());
            transferRecord.setCreateTime(importDTO.getTransferDate());

            transferRecordMapping.insertSelective(transferRecord);
        }
    }
}
